package com.pn.taikao.service.impl;

import com.pn.taikao.common.ResultCode;
import com.pn.taikao.entity.Major;
import com.pn.taikao.exception.BusinessException;
import com.pn.taikao.mapper.MajorMapper;
import com.pn.taikao.service.MajorService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MajorServiceImpl implements MajorService {

    private final MajorMapper majorMapper;

    public MajorServiceImpl(MajorMapper majorMapper) {
        this.majorMapper = majorMapper;
    }

    @Override
    public Long createMajor(Major major) {
        // 检查专业名称是否已存在
        if (StringUtils.hasText(major.getName())) {
            Major exist = majorMapper.selectByName(major.getName());
            if (exist != null) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "专业名称已存在");
            }
        }
        
        if (major.getCreateTime() == null) {
            major.setCreateTime(LocalDateTime.now());
        }
        if (major.getUpdateTime() == null) {
            major.setUpdateTime(LocalDateTime.now());
        }
        majorMapper.insert(major);
        return major.getId();
    }

    @Override
    public void updateMajor(Major major) {
        // 检查专业名称是否已存在（排除自己）
        if (StringUtils.hasText(major.getName())) {
            Major exist = majorMapper.selectByName(major.getName());
            if (exist != null && !exist.getId().equals(major.getId())) {
                throw new BusinessException(ResultCode.PARAM_ERROR, "专业名称已存在");
            }
        }
        major.setUpdateTime(LocalDateTime.now());
        majorMapper.update(major);
    }

    @Override
    public void deleteMajor(Long id) {
        majorMapper.deleteById(id);
    }

    @Override
    public Major getById(Long id) {
        return majorMapper.selectById(id);
    }

    @Override
    public List<Major> getByCollegeId(Long collegeId) {
        return majorMapper.selectByCollegeId(collegeId);
    }

    @Override
    public List<Major> list(String name, Long collegeId, int page, int size) {
        int offset = Math.max(page, 1);
        offset = (offset - 1) * Math.max(size, 1);
        return majorMapper.selectPage(name, collegeId, offset, size);
    }

    @Override
    public long count(String name, Long collegeId) {
        return majorMapper.count(name, collegeId);
    }
}













